<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/saiki.jpeg?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/saiki.jpeg?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Java,数据结构,源码,">










<meta name="description" content="HashMap在内部实际上还是以一个Node&amp;lt;K,V&amp;gt;[]的结构存储数据,只不过里面的Node结点可以指向下一个Node,因此可以构成链表或者树的结构.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647/* ---------------- Fields ------">
<meta name="keywords" content="Java,数据结构,源码">
<meta property="og:type" content="article">
<meta property="og:title" content="HashMap源码学习">
<meta property="og:url" content="http://yoursite.com/2020/06/14/HashMap源码分析/index.html">
<meta property="og:site_name" content="Penn">
<meta property="og:description" content="HashMap在内部实际上还是以一个Node&amp;lt;K,V&amp;gt;[]的结构存储数据,只不过里面的Node结点可以指向下一个Node,因此可以构成链表或者树的结构.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647/* ---------------- Fields ------">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-06-14T07:48:28.451Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="HashMap源码学习">
<meta name="twitter:description" content="HashMap在内部实际上还是以一个Node&amp;lt;K,V&amp;gt;[]的结构存储数据,只不过里面的Node结点可以指向下一个Node,因此可以构成链表或者树的结构.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647/* ---------------- Fields ------">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2020/06/14/HashMap源码分析/">





  <title>HashMap源码学习 | Penn</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Penn</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">my blog</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-schedule">
          <a href="/schedule/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-calendar"></i> <br>
            
            日程表
          </a>
        </li>
      
        
        <li class="menu-item menu-item-sitemap">
          <a href="/sitemap.xml" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br>
            
            站点地图
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br>
            
            公益404
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/06/14/HashMap源码分析/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Shen">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/saiki.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Penn">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">HashMap源码学习</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-06-14T15:48:28+08:00">
                2020-06-14
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/技术/" itemprop="url" rel="index">
                    <span itemprop="name">技术</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2020/06/14/HashMap源码分析/" class="leancloud_visitors" data-flag-title="HashMap源码学习">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>HashMap在内部实际上还是以一个Node&lt;K,V&gt;[]的结构存储数据,只不过里面的Node结点可以指向下一个Node,因此可以构成链表或者树的结构.<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line">/* ---------------- Fields -------------- */</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * The table, initialized on first use, and resized as</span><br><span class="line"> * necessary. When allocated, length is always a power of two.</span><br><span class="line"> * (We also tolerate length zero in some operations to allow</span><br><span class="line"> * bootstrapping mechanics that are currently not needed.)</span><br><span class="line"> */</span><br><span class="line">transient Node&lt;K,V&gt;[] table;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * Holds cached entrySet(). Note that AbstractMap fields are used</span><br><span class="line"> * for keySet() and values().</span><br><span class="line"> */</span><br><span class="line">transient Set&lt;Map.Entry&lt;K,V&gt;&gt; entrySet;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * The number of key-value mappings contained in this map.</span><br><span class="line"> */</span><br><span class="line">transient int size;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * The number of times this HashMap has been structurally modified</span><br><span class="line"> * Structural modifications are those that change the number of mappings in</span><br><span class="line"> * the HashMap or otherwise modify its internal structure (e.g.,</span><br><span class="line"> * rehash).  This field is used to make iterators on Collection-views of</span><br><span class="line"> * the HashMap fail-fast.  (See ConcurrentModificationException).</span><br><span class="line"> */</span><br><span class="line">transient int modCount;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * The next size value at which to resize (capacity * load factor).</span><br><span class="line"> *</span><br><span class="line"> * @serial</span><br><span class="line"> */</span><br><span class="line">// (The javadoc description is true upon serialization.</span><br><span class="line">// Additionally, if the table array has not been allocated, this</span><br><span class="line">// field holds the initial array capacity, or zero signifying</span><br><span class="line">// DEFAULT_INITIAL_CAPACITY.)</span><br><span class="line">int threshold;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * The load factor for the hash table.</span><br><span class="line"> *</span><br><span class="line"> * @serial</span><br><span class="line"> */</span><br><span class="line">final float loadFactor;</span><br></pre></td></tr></table></figure></p>
<p>HashMap的一些默认值:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">    * The default initial capacity - MUST be a power of two.</span><br><span class="line">    */</span><br><span class="line">   static final int DEFAULT_INITIAL_CAPACITY = 1 &lt;&lt; 4; // aka 16</span><br><span class="line"></span><br><span class="line">   /**</span><br><span class="line">    * The maximum capacity, used if a higher value is implicitly specified</span><br><span class="line">    * by either of the constructors with arguments.</span><br><span class="line">    * MUST be a power of two &lt;= 1&lt;&lt;30.</span><br><span class="line">    */</span><br><span class="line">   static final int MAXIMUM_CAPACITY = 1 &lt;&lt; 30;</span><br><span class="line"></span><br><span class="line">   /**</span><br><span class="line">    * The load factor used when none specified in constructor.</span><br><span class="line">    */</span><br><span class="line">   static final float DEFAULT_LOAD_FACTOR = 0.75f;</span><br><span class="line"></span><br><span class="line">   /**</span><br><span class="line">    * The bin count threshold for using a tree rather than list for a</span><br><span class="line">    * bin.  Bins are converted to trees when adding an element to a</span><br><span class="line">    * bin with at least this many nodes. The value must be greater</span><br><span class="line">    * than 2 and should be at least 8 to mesh with assumptions in</span><br><span class="line">    * tree removal about conversion back to plain bins upon</span><br><span class="line">    * shrinkage.</span><br><span class="line">    */</span><br><span class="line">   static final int TREEIFY_THRESHOLD = 8;</span><br><span class="line"></span><br><span class="line">   /**</span><br><span class="line">    * The bin count threshold for untreeifying a (split) bin during a</span><br><span class="line">    * resize operation. Should be less than TREEIFY_THRESHOLD, and at</span><br><span class="line">    * most 6 to mesh with shrinkage detection under removal.</span><br><span class="line">    */</span><br><span class="line">   static final int UNTREEIFY_THRESHOLD = 6;</span><br><span class="line"></span><br><span class="line">   /**</span><br><span class="line">    * The smallest table capacity for which bins may be treeified.</span><br><span class="line">    * (Otherwise the table is resized if too many nodes in a bin.)</span><br><span class="line">    * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts</span><br><span class="line">    * between resizing and treeification thresholds.</span><br><span class="line">    */</span><br><span class="line">   static final int MIN_TREEIFY_CAPACITY = 64;</span><br></pre></td></tr></table></figure></p>
<p>可以看出 </p>
<ul>
<li>hashMap的默认初始容量为16;</li>
<li>最大容量为<code>1 &lt;&lt; 30</code>;</li>
<li>默认负载因子为<code>DEFAULT_LOAD_FACTOR = 0.75f</code>;</li>
<li>The bin count threshold for using a tree rather than list for a bin.<code>static final int TREEIFY_THRESHOLD = 8;</code></li>
<li>The bin count threshold for untreeifying a (split) bin during a resize operation.<code>static final int UNTREEIFY_THRESHOLD = 6;</code></li>
<li><p>The smallest table capacity for which bins may be treeified.<code>static final int MIN_TREEIFY_CAPACITY = 64;</code><br><br>其中, 容量时通过<code>table</code>的大小计算的:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">final int capacity() &#123;</span><br><span class="line">        return (table != null) ? table.length :</span><br><span class="line">            (threshold &gt; 0) ? threshold :</span><br><span class="line">            DEFAULT_INITIAL_CAPACITY;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>查看put方法:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">public V put(K key, V value) &#123;</span><br><span class="line">       return putVal(hash(key), key, value, false, true);</span><br><span class="line">   &#125;</span><br><span class="line">public V putIfAbsent(K key, V value) &#123;</span><br><span class="line">       return putVal(hash(key), key, value, true, true);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>可以看到,最后都要调用<code>putVal</code>方法:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">     * Implements Map.put and related methods.</span><br><span class="line">     *</span><br><span class="line">     * @param hash hash for key</span><br><span class="line">     * @param key the key</span><br><span class="line">     * @param value the value to put</span><br><span class="line">     * @param onlyIfAbsent if true, don&apos;t change existing value</span><br><span class="line">     * @param evict if false, the table is in creation mode.</span><br><span class="line">     * @return previous value, or null if none</span><br><span class="line">     */</span><br><span class="line">    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,</span><br><span class="line">                   boolean evict) &#123;</span><br><span class="line">        Node&lt;K,V&gt;[] tab; Node&lt;K,V&gt; p; int n, i;</span><br><span class="line">        if ((tab = table) == null || (n = tab.length) == 0)</span><br><span class="line">            n = (tab = resize()).length;</span><br><span class="line">        if ((p = tab[i = (n - 1) &amp; hash]) == null)</span><br><span class="line">            tab[i] = newNode(hash, key, value, null);</span><br><span class="line">        else &#123;</span><br><span class="line">            Node&lt;K,V&gt; e; K k;</span><br><span class="line">            if (p.hash == hash &amp;&amp;</span><br><span class="line">                ((k = p.key) == key || (key != null &amp;&amp; key.equals(k))))</span><br><span class="line">                e = p;</span><br><span class="line">            else if (p instanceof TreeNode)</span><br><span class="line">                e = ((TreeNode&lt;K,V&gt;)p).putTreeVal(this, tab, hash, key, value);</span><br><span class="line">            else &#123;</span><br><span class="line">                for (int binCount = 0; ; ++binCount) &#123;</span><br><span class="line">                    if ((e = p.next) == null) &#123;</span><br><span class="line">                        p.next = newNode(hash, key, value, null);</span><br><span class="line">                        if (binCount &gt;= TREEIFY_THRESHOLD - 1) // -1 for 1st</span><br><span class="line">                            treeifyBin(tab, hash);</span><br><span class="line">                        break;</span><br><span class="line">                    &#125;</span><br><span class="line">                    if (e.hash == hash &amp;&amp;</span><br><span class="line">                        ((k = e.key) == key || (key != null &amp;&amp; key.equals(k))))</span><br><span class="line">                        break;</span><br><span class="line">                    p = e;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            if (e != null) &#123; // existing mapping for key</span><br><span class="line">                V oldValue = e.value;</span><br><span class="line">                if (!onlyIfAbsent || oldValue == null)</span><br><span class="line">                    e.value = value;</span><br><span class="line">                afterNodeAccess(e);</span><br><span class="line">                return oldValue;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        ++modCount;</span><br><span class="line">        if (++size &gt; threshold)</span><br><span class="line">            resize();</span><br><span class="line">        afterNodeInsertion(evict);</span><br><span class="line">        return null;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p>
<p>从上面的代码中我们可以看出hashMap添加节点时的扩容策略和<code>treeifyBin</code>策略.</p>
<ul>
<li><p>扩容<br></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">if (++size &gt; threshold)</span><br><span class="line">           resize();</span><br></pre></td></tr></table></figure>
<p>如果新节点的<code>key</code>之前在<code>map</code>里不存在,那么<code>size</code>就会<code>+1</code>,当<code>size</code>大于<code>threshold</code>之后,会调用<code>resize()</code>方法.<br><br>之前看网上分析都是在size大于容量乘以loadFactor后就开始扩容,这里直接比较的是size和threshold的大小.似乎有一点不一样,继续看resize()的代码:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"> final Node&lt;K,V&gt;[] resize() &#123;</span><br><span class="line">    Node&lt;K,V&gt;[] oldTab = table;</span><br><span class="line">    int oldCap = (oldTab == null) ? 0 : oldTab.length;</span><br><span class="line">    int oldThr = threshold;</span><br><span class="line">    int newCap, newThr = 0;</span><br><span class="line">    if (oldCap &gt; 0) &#123;</span><br><span class="line">        if (oldCap &gt;= MAXIMUM_CAPACITY) &#123;</span><br><span class="line">            threshold = Integer.MAX_VALUE;</span><br><span class="line">            return oldTab;</span><br><span class="line">        &#125;</span><br><span class="line">        else if ((newCap = oldCap &lt;&lt; 1) &lt; MAXIMUM_CAPACITY &amp;&amp;</span><br><span class="line">                 oldCap &gt;= DEFAULT_INITIAL_CAPACITY)</span><br><span class="line">            newThr = oldThr &lt;&lt; 1; // double threshold</span><br><span class="line">    &#125;</span><br><span class="line">    else if (oldThr &gt; 0) // initial capacity was placed in threshold</span><br><span class="line">        newCap = oldThr;</span><br><span class="line">    else &#123;               // zero initial threshold signifies using defaults</span><br><span class="line">        newCap = DEFAULT_INITIAL_CAPACITY;</span><br><span class="line">        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);</span><br><span class="line">    &#125;</span><br><span class="line">    if (newThr == 0) &#123;</span><br><span class="line">        float ft = (float)newCap * loadFactor;</span><br><span class="line">        newThr = (newCap &lt; MAXIMUM_CAPACITY &amp;&amp; ft &lt; (float)MAXIMUM_CAPACITY ?</span><br><span class="line">                  (int)ft : Integer.MAX_VALUE);</span><br><span class="line">    &#125;</span><br><span class="line">    threshold = newThr;</span><br><span class="line">    @SuppressWarnings(&#123;&quot;rawtypes&quot;,&quot;unchecked&quot;&#125;)</span><br><span class="line">    Node&lt;K,V&gt;[] newTab = (Node&lt;K,V&gt;[])new Node[newCap];</span><br><span class="line">    table = newTab;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我们可以看到,当map里面添加第一个元素时:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">newCap = DEFAULT_INITIAL_CAPACITY;     // 容量</span><br><span class="line">newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); //threshold</span><br></pre></td></tr></table></figure>
<p>将容量设置成<code>DEFAULT_INITIAL_CAPACITY</code>,<code>threshold</code>设置成 <code>(int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);</code><br>之后,每次容量和threshold都是成倍增加,因此:<br><br><code>容量 = threshold * loadFactor</code>,扩容判断条件和网上分析的是一样的.<br><br>也说明了hashMap和Arrlist一样,一开始都是用的一个空数字,在加入第一个元素的时候,才会初始化数组大小.</p>
</li>
</ul>
<ul>
<li>hash冲突时的处理方法<br>把新元素加到table数组中时,如果加入位置上已有元素,如果两者key相同,则用新value覆盖旧value.否则,会将新元素加到该位置上的树或者链表上:<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">if (p.hash == hash &amp;&amp;</span><br><span class="line">               ((k = p.key) == key || (key != null &amp;&amp; key.equals(k))))</span><br><span class="line">               e = p;</span><br><span class="line">           else if (p instanceof TreeNode)</span><br><span class="line">               e = ((TreeNode&lt;K,V&gt;)p).putTreeVal(this, tab, hash, key, value);</span><br><span class="line">           else &#123;</span><br><span class="line">               for (int binCount = 0; ; ++binCount) &#123;</span><br><span class="line">                   if ((e = p.next) == null) &#123;</span><br><span class="line">                       p.next = newNode(hash, key, value, null);</span><br><span class="line">                       //判断是否需要把链表转成红黑树</span><br><span class="line">                       if (binCount &gt;= TREEIFY_THRESHOLD - 1) // -1 for 1st</span><br><span class="line">                           treeifyBin(tab, hash);</span><br><span class="line">                       break;</span><br><span class="line">                   &#125;</span><br><span class="line">                   if (e.hash == hash &amp;&amp;</span><br><span class="line">                       ((k = e.key) == key || (key != null &amp;&amp; key.equals(k))))</span><br><span class="line">                       break;</span><br><span class="line">                   p = e;</span><br><span class="line">               &#125;</span><br><span class="line">           &#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>当链表上<code>Node&lt;K&lt;V&gt;</code>的数量大于或等于<code>TREEIFY_THRESHOLD</code>时,链表就换转换成红黑树.链表上的结点转换成<code>TreeNode&lt;K,V&gt;</code>.</p>
<p><code>LinkedHashMap</code>的有序性是因为它的<code>node</code>继承了<code>HashMap</code>的<code>node</code>,多加了<code>before</code>和<code>after</code>属性,构成了一条双向链表:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">    * HashMap.Node subclass for normal LinkedHashMap entries.</span><br><span class="line">    */</span><br><span class="line">   static class Entry&lt;K,V&gt; extends HashMap.Node&lt;K,V&gt; &#123;</span><br><span class="line">       Entry&lt;K,V&gt; before, after;</span><br><span class="line">       Entry(int hash, K key, V value, Node&lt;K,V&gt; next) &#123;</span><br><span class="line">           super(hash, key, value, next);</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="hashMap中key的位置是怎么算的"><a href="#hashMap中key的位置是怎么算的" class="headerlink" title="hashMap中key的位置是怎么算的?"></a>hashMap中key的位置是怎么算的?</h4><p>首先是计算key的hash值<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">static final int hash(Object key) &#123;</span><br><span class="line">       int h;</span><br><span class="line">       return (key == null) ? 0 : (h = key.hashCode()) ^ (h &gt;&gt;&gt; 16);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<p>这里<code>key.hashCode()</code>之后为什么还要对高16位取抑或运算呢?<br><br>先看下一步取位置<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">tab[i = (n - 1) &amp; hash])</span><br></pre></td></tr></table></figure></p>
<p>这里取<code>(n-1) &amp; hash</code>很巧妙,因为n是2的整次幂,所以<code>n-1</code>比如15二进制表示就是<code>1111</code>,和<code>hash</code>的<code>&amp;</code>运算就相当于是取模了,但是又比<code>%</code>运算快.<br><br>但是有一个问题,hash的高位没有用上,这样就会造成hash冲突的概率变大.<br><br>所以,算hash值的时候,先用高16位与低16位取抑或,这样就能降低hash冲突的概率了.</p>
<h4 id="hashMap的容量为什么必须是2的n次幂"><a href="#hashMap的容量为什么必须是2的n次幂" class="headerlink" title="hashMap的容量为什么必须是2的n次幂?"></a>hashMap的容量为什么必须是2的n次幂?</h4><p>这是因为扩容时,会重新计算所有旧的Node的位置.<br><br>假如旧的容量是<code>a</code>,那么新的容量就是<code>2a</code><br><br>原来在<code>j</code>位置上的node新位置只有两种情况:<br><code>j</code>或者<code>a+j</code><br><br>因为旧的那些结点模<code>a</code>等于<code>j</code>,那么模<code>2a</code>必然等于<code>j</code>或者<code>a+j</code>,这样扩容时,同一位置的node就可以分成两批移动了,提高扩容效率.<br><br>而且计算新位置的这里的算法特别巧妙:<br><br>假设原来的大小是16,有两个元素在一个位置:2和18,它们和<code>16-1`</code>&amp;<code>运算&lt;br&gt;</code>0000 0010<code>和</code>0001 0010<code>&lt;br&gt;</code>0000 1111<code>--</code>0000 1111<code>&lt;br&gt;
要判断他们的新位置,不需要和</code>32-1<code>进行</code>&amp;<code>运算,只需要和</code>32<code>进行</code>&amp;<code>运算看高一位是0还是1就行了,这样很方便的就能将他们均匀的分散开.</code>0000 0010<code>和</code>0001 0010<code>&lt;br&gt;</code>0001 0000<code>--</code>0001 0000` <br><br>源码:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">    do &#123;</span><br><span class="line">        next = e.next;</span><br><span class="line">        //注意,这里没有和(oldGap-1)进行`&amp;`运算 只有等于0和oldCap两种结果</span><br><span class="line">        if ((e.hash &amp; oldCap) == 0) &#123;</span><br><span class="line">            if (loTail == null)</span><br><span class="line">                loHead = e;</span><br><span class="line">            else</span><br><span class="line">                loTail.next = e;</span><br><span class="line">            loTail = e;</span><br><span class="line">        &#125;</span><br><span class="line">        else &#123;</span><br><span class="line">            if (hiTail == null)</span><br><span class="line">                hiHead = e;</span><br><span class="line">            else</span><br><span class="line">                hiTail.next = e;</span><br><span class="line">            hiTail = e;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; while ((e = next) != null);</span><br><span class="line">    if (loTail != null) &#123;</span><br><span class="line">        loTail.next = null;</span><br><span class="line">        newTab[j] = loHead;</span><br><span class="line">    &#125;</span><br><span class="line">    if (hiTail != null) &#123;</span><br><span class="line">        hiTail.next = null;</span><br><span class="line">        newTab[j + oldCap] = hiHead;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="默认负载因子为什么是0-75"><a href="#默认负载因子为什么是0-75" class="headerlink" title="默认负载因子为什么是0.75"></a>默认负载因子为什么是0.75</h4><ol>
<li>假如负载因子是1,那么数组满了才会扩容,但很多情况下,数组满了很大概率会存在hash冲突,,hash值算出的索引分布不一定是分布在数组的每一个位置,有了hash冲突之后,就会形成链表或者红黑树,这样查询效率就降低了.</li>
<li>假如负载因子是0.5,那么数组空间用到了一半就得扩容,然后就得重新计算所有node的新位置,虽然查询变快了,但是空间利用率降低了.<br></li>
</ol>
<p>所以官方用了综合表现比较好的0.75.</p>
<h4 id="hashMap不是线程安全的"><a href="#hashMap不是线程安全的" class="headerlink" title="hashMap不是线程安全的"></a>hashMap不是线程安全的</h4><p>在1.7中,hash冲突时,链表插入采用的时头插法,比如多线程对容量为2的数组依次put 5,3,7会产生7-》3-》5这种结构,然后扩容成4,将node加到新位置,有可能造成3—》7-》3的循环.</p>
<p>在1.8中,两个线程分别put 3和7<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">if ((p = tab[i = (n - 1) &amp; hash]) == null)</span><br><span class="line">         tab[i] = newNode(hash, key, value, null);</span><br></pre></td></tr></table></figure></p>
<p>如果hash计算出的索引位置上没有node的话,就有可能造成数据覆盖,丢失了一部分数据.还有<code>resize</code>时插入删除等.</p>
<h4 id="为什么树化的阈值是8"><a href="#为什么树化的阈值是8" class="headerlink" title="为什么树化的阈值是8?"></a>为什么树化的阈值是8?</h4><p>根据官方注释:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">Ideally, under random hashCodes, the frequency of</span><br><span class="line">     * nodes in bins follows a Poisson distribution</span><br><span class="line">     * (http://en.wikipedia.org/wiki/Poisson_distribution) with a</span><br><span class="line">     * parameter of about 0.5 on average for the default resizing</span><br><span class="line">     * threshold of 0.75, although with a large variance because of</span><br><span class="line">     * resizing granularity. Ignoring variance, the expected</span><br><span class="line">     * occurrences of list size k are (exp(-0.5) * pow(0.5, k) /</span><br><span class="line">     * factorial(k)). The first values are:</span><br><span class="line">     *</span><br><span class="line">     * 0:    0.60653066</span><br><span class="line">     * 1:    0.30326533</span><br><span class="line">     * 2:    0.07581633</span><br><span class="line">     * 3:    0.01263606</span><br><span class="line">     * 4:    0.00157952</span><br><span class="line">     * 5:    0.00015795</span><br><span class="line">     * 6:    0.00001316</span><br><span class="line">     * 7:    0.00000094</span><br><span class="line">     * 8:    0.00000006</span><br><span class="line">     * more: less than 1 in ten million</span><br></pre></td></tr></table></figure></p>
<p>理想情况下,容器中的结点符合泊松分布,链表长度大于8的情况特别小,所以选了8来做阈值.而且,当链表长度为大于8时,链表的平均查询时间大于<code>8/2=4</code>,比红黑树的平均查询时间<code>lg8=3</code>要大,这时候转成红黑树就能提高查询效率了.<br>而且,TreeNode需要记录praent、left、right等值,比Node占空间,所以小于6的时候,转成链表比较好.</p>
<h4 id="hashMap和HashTable的区别"><a href="#hashMap和HashTable的区别" class="headerlink" title="hashMap和HashTable的区别"></a>hashMap和HashTable的区别</h4><ol>
<li>hashTable的初始大小为11,每次扩容2n+1</li>
<li>hashTable里的大部分方法都用<code>synchronized</code>修饰,是线程安全的</li>
<li>hashTable不允许key是null,hashMap允许.</li>
<li>hashTable是数组加链表存数据,没有红黑树</li>
<li>单线程下hashMap效率高,hashTable基本被淘汰了,为了线程安全可以用ConcurrentHashMap</li>
</ol>
<h4 id="LinkedHashMap"><a href="#LinkedHashMap" class="headerlink" title="LinkedHashMap"></a>LinkedHashMap</h4><p>LinkedHashMap继承自HashMap,所以底层存储结构差不多,但比它多了一条双链表保证有序性</p>
<h4 id="hashSet"><a href="#hashSet" class="headerlink" title="hashSet"></a>hashSet</h4><p><code>hashSet</code>实际上也是借用<code>hashMap</code>来存值的.<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">private transient HashMap&lt;E,Object&gt; map;</span><br><span class="line"></span><br><span class="line">public HashSet() &#123;</span><br><span class="line">        map = new HashMap&lt;&gt;();</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>这两个图片是什么?可以扫吗?</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatPay.png" alt="Shen 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/aliPay.png" alt="Shen 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Java/" rel="tag"># Java</a>
          
            <a href="/tags/数据结构/" rel="tag"># 数据结构</a>
          
            <a href="/tags/源码/" rel="tag"># 源码</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/06/14/ArrayList、LinkedList和Vector/" rel="next" title="ArrayList、LinkedList和Vector">
                <i class="fa fa-chevron-left"></i> ArrayList、LinkedList和Vector
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/06/14/ConcurrentHashMap/" rel="prev" title="ConcurrentHashMap">
                ConcurrentHashMap <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MjA1OS8xODYwNg=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/saiki.jpeg" alt="Shen">
            
              <p class="site-author-name" itemprop="name">Shen</p>
              <p class="site-description motion-element" itemprop="description">Penn's blog</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">117</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">26</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#hashMap中key的位置是怎么算的"><span class="nav-number">1.</span> <span class="nav-text">hashMap中key的位置是怎么算的?</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#hashMap的容量为什么必须是2的n次幂"><span class="nav-number">2.</span> <span class="nav-text">hashMap的容量为什么必须是2的n次幂?</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#默认负载因子为什么是0-75"><span class="nav-number">3.</span> <span class="nav-text">默认负载因子为什么是0.75</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#hashMap不是线程安全的"><span class="nav-number">4.</span> <span class="nav-text">hashMap不是线程安全的</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#为什么树化的阈值是8"><span class="nav-number">5.</span> <span class="nav-text">为什么树化的阈值是8?</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#hashMap和HashTable的区别"><span class="nav-number">6.</span> <span class="nav-text">hashMap和HashTable的区别</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#LinkedHashMap"><span class="nav-number">7.</span> <span class="nav-text">LinkedHashMap</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#hashSet"><span class="nav-number">8.</span> <span class="nav-text">hashSet</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Shen</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("Gst71Gv0w5HKejm5H7LuG0XI-gzGzoHsz", "aoFAyHFDKihGTWWhHX0p8byC");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
